package conv

import (
	"fmt"
	"math"
	"reflect"
	"strconv"
	"strings"
	"unsafe"
)

func AnyToInt(d any) int {
	switch d.(type) {
	case int:
		return d.(int)
	case int32:
		return d.(int)
	case int64:
		v := d.(int64)
		return *(*int)(unsafe.Pointer(&v))
	case float64:
		v := d.(float64)
		return int(math.Floor(v + 0.5))
	case string:
		v := d.(string)

		//处理小数
		if strings.Contains(v, ".") {
			in, err := strconv.ParseFloat(v, 64)
			if err != nil {
				fmt.Println(err.Error())
				return 0
			}
			return int(math.Floor(in + 0.5))
		}

		//处理整数
		in, err := strconv.ParseInt(v, 10, 32)

		if err != nil {
			return 0
		}
		return int(in)
	default:
		return 0
	}
}
func Bytes2String(b []byte) string {
	//return unsafe.String(&b[0], unsafe.IntegerType(len(b)))
	sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&b))
	sh := reflect.StringHeader{
		Data: sliceHeader.Data,
		Len:  sliceHeader.Len,
	}
	return *(*string)(unsafe.Pointer(&sh))
}
func String2Bytes(s string) []byte {
	//return unsafe.Slice(unsafe.StringData(s), len(s))
	stringHeader := (*reflect.StringHeader)(unsafe.Pointer(&s))
	bh := reflect.SliceHeader{
		Data: stringHeader.Data,
		Len:  stringHeader.Len,
		Cap:  stringHeader.Len,
	}
	return *(*[]byte)(unsafe.Pointer(&bh))
}
